#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define FILENAME "/tmp/out"

static void daemonize(void)
{
  pid_t pid;
  int fd;;
  if ((pid = fork()) < 0) {
    perror("fork");
    exit(1);
  }

  if (pid == 0) { // child process
    if ((fd = open("/dev/null", O_RDWR)) < 0) {
      perror("open");
      exit(1);
    }
    dup2(fd, 0);
    dup2(fd, 1);
    dup2(fd, 2);
    if (fd > 2)
      close(fd);

    setsid();

    // change working directory
    chdir("/"); // preventing "device is busy"
    // umask(0);
    return;
  } else {
    exit(0);
    // the daemon process's parent will be the init process
  }
}

int main()
{
  FILE* fp = NULL;

  // init daemon process
  daemonize();

  // the task of daemon process
  if ((fp = fopen(FILENAME, "w")) == NULL) {
    perror("fopen");
    exit(1);
  }
  
  for (int i = 0; ; i++) {
    fprintf(fp, "%d\n", i);
    fflush(fp); // writting file is full buffer, so we should flush the buffer after printf()
    sleep(1);
  }

  exit(0);
}
